import { getEvaluationInfo, getTemplateInfo, loadingEvaluationInfo } from "@/api/partyBuilding";
import { tipsMessage } from "@/utils/messageConfig";
import { ref } from "vue";
import { useRoute } from "vue-router";
import {
  MAX_COL_NUM,
  DEFAULT_COLUMN_MOA,
  REQUIRED_TYPE,
  DEFAULT_COORDINATE,
  MOA_IDENTITY,
  DEVICE_TYPE,
  ERROR_MESSAGE,
  BEAUTIFUL_MOBILE_NAME,
  MODULE_TYPE,
} from "@/utils/mockConfiguration/mockConfig";
import { useTemplateEditing } from "@/store/modules/templateEditing";

const { QUESTION_MODULE } = MODULE_TYPE;
const { DESKTOP } = DEVICE_TYPE;
const { ERROR_MOA_ACCESS } = ERROR_MESSAGE;
const templateEditing = useTemplateEditing();
const { currentSettings, votingData, submitButton, optionalQuestionRules, requiredQuestionRules, disabledQuestionRules } =
  storeToRefs(templateEditing);
//接口配置信息
const CONFIGURATION = {
  edit: getTemplateInfo, //编辑流程接口
  preview: getTemplateInfo, //预览流程接口
  allots: getEvaluationInfo, //下发流程接口
  loading: loadingEvaluationInfo, //提交流程接口
};

/**
 * 初始化规则
 */
export default function useInitializationMethod() {
  const mxSsoToken = ref(""); //moa的认证token

  onMounted(() => {
    const route = useRoute();
    const { id, mx_sso_token } = route.query;
    currentSettings.value.id = id;
    mxSsoToken.value = mx_sso_token ?? "";
  });

  const RULE_MAP = {
    optional: optionalQuestionRules, // 选答题规则
    required: requiredQuestionRules, // 必答题规则
    disabled: disabledQuestionRules, // 禁答题规则
  };

  const init = async props => {
    const { id: templateId } = currentSettings.value;
    const isMoa = templateId.includes(MOA_IDENTITY);
    //没ID的时候，不请求接口,如果模板ID包含moa使用的token，提示信息。
    if (!templateId || isMoa) {
      isMoa && tipsMessage({ type: "error", message: ERROR_MOA_ACCESS });
      return;
    }

    // 请求配置数据
    const params = {
      id: templateId,
      mxSsoToken: mxSsoToken.value,
    };

    const {
      data: { id, name, modules, groupConfig, baseConfig },
    } = await CONFIGURATION[props.deliveryStatus](params);

    submitButton.value = true; //显示提交
    // 显示提交按钮并更新页面标题
    if (submitButton.value) {
      document.title = name;
    }

    // 解析模块数据
    const parseModuleItem = ({ cssStyle, businessData, ...rest }) => ({
      ...rest,
      cssStyle: JSON.parse(cssStyle),
      businessData: JSON.parse(businessData),
    });

    const newModules = JSON.parse(modules).map(parseModuleItem);
    //投票数据收集
    votingData.value = newModules.filter(item => QUESTION_MODULE.includes(item.moduleId));

    // 过滤投票数据并处理关联规则
    const handleVotingData = ({ businessData }) => {
      const { id, selectRule, assocRules } = businessData;
      businessData.required = selectRule === REQUIRED_TYPE;
      assocRules?.forEach(rule => {
        rule.objectId = id;
        RULE_MAP[rule.relation]?.value.push(rule);
      });
    };

    votingData.value.forEach(handleVotingData);

    /**
     * 获取移动端模块位置
     * @param x X坐标
     * @param y Y坐标
     * @param h 高度
     * @param columnWidth 列宽度
     */
    const getPosition = (x, y, h, columnWidth) => {
      return {
        0: { x: DEFAULT_COORDINATE },
        5: { x: columnWidth },
        10: { x: 0, y: y + h },
        15: { x: columnWidth, y: y + h },
      }[x];
    };

    /**
     * 移动端的最美移动人模块转换
     * @param newModules
     */
    const formatConversion = newModules => {
      if (props.terminalType === DESKTOP) {
        return newModules;
      }
      const columnWidth = MAX_COL_NUM / DEFAULT_COLUMN_MOA;
      return newModules.map(item => {
        if (item.moduleId !== BEAUTIFUL_MOBILE_NAME) {
          return item;
        }
        const {
          cssStyle: { x, y, h },
        } = item;
        return {
          ...item,
          cssStyle: {
            ...item.cssStyle,
            w: columnWidth,
            ...getPosition(x, y, h, columnWidth),
          },
        };
      });
    };

    /**
     * 配置数据格式化
     */
    currentSettings.value = {
      ...currentSettings.value,
      id,
      name,
      modules: formatConversion(newModules),
      groupConfig: JSON.parse(groupConfig),
      baseConfig: JSON.parse(baseConfig),
    };
  };
  return {
    init, //初始化
  };
}
